const mongoose = require('mongoose');
//const bcrypt = require('bcrypt');
const bcrypt = require('bcrypt-nodejs');
const jwt = require('jsonwebtoken');
const MongoUser = require('../models/user');

const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const generateMixed = (n) => {
    var res = "";
    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}
exports.user_verify = (req, res, next) => {
    const random = generateMixed(4);
    req.session.verifyCode=random;//验证码有效期1分钟
    res.status(200).json({
        code:random
    })
}
exports.user_signup = (req, res, next) => {
    //console.log(req.session);
    MongoUser.find({ phone: req.body.phone }).exec().then(user => {
        if (user.length >= 1) {
            return res.status(409).json({
                message: 'user exists'
            })
        } else if(req.body.verifyCode!=req.session.verifyCode) {
            return res.status(409).json({
                message: 'verify error'
            })
        }else{
            bcrypt.hash(req.body.password, null, null, (err, hash) => {
                if (err) {
                    return res.status(500).json({
                        message: 'bcrypt failed',
                        error: err
                    })
                } else {
                    const user = new MongoUser({
                        _id: new mongoose.Types.ObjectId(),
                        username: req.body.username,
                        phone: req.body.phone,
                        address: req.body.address,
                        //email: req.body.email,
                        password: hash
                    })
                    user.save().then(result => {
                        res.status(201).json({
                            message: 'user created'
                        })
                    }).catch(err => {
                        res.status(500).json({
                            message: 'user created failed',
                            error: err
                        })
                    })
                }
            })
        }
    }).catch(err => {
        res.status(500).json(err)
    })
}
exports.user_login = (req, res, next) => {
    //console.log(req.body)
    MongoUser.find({ phone: req.body.phone }).exec().then(user => {
        bcrypt.compare(req.body.password, user[0].password, (err, result) => {
            if (err) {
                return res.status(500).json(err)
            }
            const token = jwt.sign({
                uid: user[0]._id,
                username: user[0].username,
                phone: user[0].phone,
                address: user[0].address
            }, process.env.JWT_KEY, {
                    expiresIn: '2h'
                })
            if (result) {
                return res.status(200).json({
                    message: 'auth success',
                    token: token
                })
            }
        })
    }).catch(err => {
        res.status(500).json({message:'account or password is wrong'})
    })
}
exports.user_logout = (req, res, next) => {
    req.headers.token = null;
    //delete req.session.user
}
exports.user_delete = (req, res, next) => {
    const uid = req.params.uid;
    MongoUser.remove({ _id: uid }).exec().then(result => {
        res.status(200).json({
            message: 'user deleted'
        })
    }).catch(err => {
        res.status(500).json(err)
    })
}